<template>
  <div class="container">
    <a-col class="banner">
      <a-col :span="8">
        <a-typography-title :heading="5" style="margin-top: 0">
          {{ $t('欢迎' + '来到扫描台！' ) }} 
        </a-typography-title>
      </a-col>
      <a-divider class="panel-border" />
      <div class="video-container">
        <video ref="videoRef" :src="videoSrc" controls @error="handleVideoError" @loadeddata="handleVideoLoaded"></video>
        <div v-if="videoLoadingError" class="video-error-message">视频还没处理</div>
      </div>
      <div class="btn-container">
        <a-button type="primary" :loading="loadingPrev" @click="handlePrevVideo">上一次</a-button>
        <a-button type="primary" :loading="loadingNext" @click="handleNextVideo">下一次</a-button>
      </div>
      <div class="saomiao-text">
        感谢使用扫描台
      </div>
    </a-col>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';
import { IconPlus } from '@arco-design/web-vue/es/icon';
import axios from 'axios';
import { Message } from '@arco-design/web-vue'; // 引入 Arco Design 的消息提示组件
import {handleError} from '@/utils/Ding.js'

export default {
  components: {
    IconPlus
  },
  setup() {
    
    const currentVideoIndex = ref(null); 
    const totalVideoCount = ref(null); // 新增变量保存总视频数量
    const loadingPrev = ref(false);
    const loadingNext = ref(false);
    const ENV = 'http://localhost:8000/';
    const videoSrc = ref('');
    const videoRef = ref(null);
    const videoLoadingError = ref(false);
    let videoLoadTimeout;
    const storedUserInfo = localStorage.getItem('userInfo');
    let parsedUserInfo = ""
    if (storedUserInfo) {
        parsedUserInfo = JSON.parse(storedUserInfo);
    }
    const fetchCount = async () => {
      try {
        const response = await axios.get(`http://localhost:8089/fridge/getCount/${parsedUserInfo.userbid}`);
        const totalCount = response.data.data;
        if (typeof totalCount === 'number' && totalCount > 0) {
          totalVideoCount.value = totalCount; // 保存总视频数量
          currentVideoIndex.value = totalCount; 
          videoSrc.value = `${ENV}runs/${parsedUserInfo.userbid}/exp${currentVideoIndex.value}/output0.mp4`;
        } else {
          let error = {
            message: '获取数量失败，可能是没有打开Yolo服务器',
            statusCode: response.status, // 假设状态码可以从 response 中获取
            method: 'GET',
            path: '/fridge/getCount/${parsedUserInfo.userbid}',
            fullUrl: `http://localhost:8089/fridge/getCount/${parsedUserInfo.userbid}`,
            time: new Date().toISOString(),
            params: {} // 假设这里没有请求参数
          };
          handleError(error);
        }
      } catch (error) {
        console.error('获取数量失败:', error);
      }
    };

    onMounted(() => {
      fetchCount();
    });

    const handlePrevVideo = () => {
      if (currentVideoIndex.value === null) return;
      loadingPrev.value = true;
      if (currentVideoIndex.value > 0) {
        currentVideoIndex.value--;
        videoSrc.value = `${ENV}runs/${parsedUserInfo.userbid}/exp${currentVideoIndex.value}/output0.mp4`;
        startVideoLoadTimer();
      }else{
        Message.warning('已经是第一个视频，无法继续上一个'); // 给出提示
      }
      loadingPrev.value = false;
    };

    const handleNextVideo = () => {
      if (currentVideoIndex.value === null || totalVideoCount.value === null) return;
      loadingNext.value = true;
      if (currentVideoIndex.value < totalVideoCount.value - 1) {
        currentVideoIndex.value++;
        videoSrc.value = `${ENV}runs/${parsedUserInfo.userbid}/exp${currentVideoIndex.value}/output0.mp4`;
        startVideoLoadTimer();
      } else {
        Message.warning('已经是最后一个视频，无法继续下一个'); // 给出提示
      }
      loadingNext.value = false;
    };

    const startVideoLoadTimer = () => {
      videoLoadingError.value = false;
      clearTimeout(videoLoadTimeout);
      videoLoadTimeout = setTimeout(() => {
        videoLoadingError.value = true;
      }, 2000);
    };

    const handleVideoLoaded = () => {
      clearTimeout(videoLoadTimeout);
      videoLoadingError.value = false;
    };

    const handleVideoError = () => {
      clearTimeout(videoLoadTimeout);
      Message.warning('视频还没处理哦 ～ '); // 给出提示
      videoLoadingError.value = true;
    };

    onUnmounted(() => {
      clearTimeout(videoLoadTimeout);
    });

    return {
      videoSrc,
      loadingPrev,
      loadingNext,
      handlePrevVideo,
      handleNextVideo,
      videoRef,
      videoLoadingError
    };
  }
};
</script>

<style scoped lang="less">
.container {
    background-color: var(--color-fill-2);
    padding: 16px 20px;
    padding-bottom: 0;
  }
.banner {
  width: 100%;
  padding: 20px 20px 0 20px;
  background-color: var(--color-bg-2);
  height: 850px;
  border-radius: 4px 4px 0 0;
}

:deep(.arco-icon-home) {
  margin-right: 6px;
}
.video-container{
  width: 60%;
  margin: 30px auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
  video{
    width: 100%;
    height: 100%;
  }
  .video-error-message {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: red;
    font-weight: bold;
  }
}
.btn-container{
  width: 60%;
  margin: 25px auto;
  display: flex;
  justify-content: space-between;
  button{
    width: 45%;
  }
}
.saomiao-text{
  margin: 200px auto;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}
</style>